<template>
  <div class="app-container" style="background: rgb(248, 248, 248)">
    <div class="header">
      <span class="header-time">{{ currentTime }} | {{ currentCity }}</span>
    </div>
    <div class="mood-input">
      <select v-model="mood">
        <option value="5">难过</option>
        <option value="4">伤心</option>
        <option value="3">一般</option>
        <option value="2">开心</option>
        <option value="1">狂喜</option>
      </select>
      <input type="text" v-model="moodText" placeholder="书写你的心情" />
      <button @click="recordMood">记录</button>
    </div>

    <div
      class="timeline"
      style="height: 55vh; overflow-y: auto; overflow-x: hidden"
    >
      <div class="" v-for="(record, index) in records" :key="index">
        <span class="timeline-date">{{ record.time }}</span>
        <div class="timeline-item">
          <div style="display: flex; align-items: center; width: 10%">
            <img
              src="@/assets/1.png"
              v-if="record.moodIndex == 5"
              style="width: 40px"
            />
            <img
              src="@/assets/2.png"
              v-if="record.moodIndex == 4"
              style="width: 40px"
            />
            <img
              src="@/assets/3.png"
              v-if="record.moodIndex == 3"
              style="width: 40px"
            />
            <img
              src="@/assets/4.png"
              v-if="record.moodIndex == 2"
              style="width: 40px"
            />
            <img
              src="@/assets/5.png"
              v-if="record.moodIndex == 1"
              style="width: 40px"
            />
            <!-- <span class="timeline-mood">{{
                record.moodIndex == 1
                  ? "狂喜"
                  : record.moodIndex == 2
                  ? "开心"
                  : record.moodIndex == 3
                  ? "一般"
                  : record.moodIndex == 4
                  ? "伤心"
                  : "难过"
              }}</span> -->
          </div>
          <div style="width: 90%">
            <div class="timeline-item-header">
              <span class="timeline-date">{{ record.creatTime }}</span>
            </div>
            <div class="timeline-item-content">
              <span class="timeline-text" v-if="!record.isdelFun">{{
                record.description
              }}</span>
              <span class="timeline-text" v-if="record.isdelFun">
                <input v-model="record.description" />
              </span>
            </div>
          </div>
          <div
            style="display: flex; align-items: center; cursor: pointer"
            @click="delFun(record)"
          >
            <svg
              t="1744693859839"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="2288"
              width="16"
              height="16"
            >
              <path
                d="M684.202667 117.248c15.893333-15.872 42.154667-15.36 58.922666 1.408l90.517334 90.517333c16.661333 16.661333 17.344 42.986667 1.429333 58.922667l-445.653333 445.653333c-7.936 7.914667-23.104 16.746667-34.218667 19.776l-143.701333 39.253334c-21.909333 5.994667-35.114667-7.104-29.568-28.949334l37.248-146.773333c2.773333-10.944 11.562667-26.346667 19.392-34.176l445.653333-445.653333zM268.736 593.066667c-2.901333 2.901333-8.106667 12.074667-9.130667 16.021333l-29.12 114.773333 111.957334-30.570666c4.437333-1.216 13.632-6.549333 16.810666-9.728l445.653334-445.653334-90.517334-90.496-445.653333 445.653334zM682.794667 178.986667l90.517333 90.517333-30.186667 30.186667-90.496-90.517334 30.165334-30.165333z m-362.026667 362.048l90.496 90.517333-30.165333 30.165333-90.517334-90.496 30.165334-30.186666zM170.666667 874.666667c0-11.776 9.429333-21.333333 21.461333-21.333334h661.077333a21.333333 21.333333 0 1 1 0 42.666667H192.128A21.333333 21.333333 0 0 1 170.666667 874.666667z"
                fill="#3D3D3D"
                p-id="2289"
              ></path>
            </svg>
          </div>
        </div>
      </div>
    </div>
    <div>
      <div style="margin-top: 20px">
        {{ typeList == 'thisWeek'?'周视图':typeList == 'thisMonth'?'月视图':typeList == 'thisYear'?'年视图':"" }}
        <button style="margin: 1vh" @click="initChart('thisWeek')">周</button>
        <button style="margin: 1vh" @click="initChart('thisMonth')">月</button>
        <button style="margin: 1vh" @click="initChart('thisYear')">年</button>
      </div>
      <div ref="chartRef" style="width: 80vw; height: 20vh"></div>
    </div>
  </div>
</template>

<script setup name="moodIndex">
import { onMounted, ref,reactive } from "vue";
import * as echarts from "echarts";
import { selectMood, addMood, updateMood, histogram } from "@/api/Login";
// 数据定义（与之前相同）
const columns = [
    // 列定义省略，与之前相同
  ];
  
  const genderMap = { 1: '男', 2: '女' };
  
  const schoolOptions = [
    { value: 'school1', label: '第一实验小学' },
    // 其他学校选项省略
  ];
  
  const gradeOptions = [
    { value: 'grade1', label: '一年级' },
    // 其他年级选项省略
  ];
  
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50'],
    showTotal: total => `共 ${total} 条数据`,
  });
  
  const formState = reactive({
    id: null,
    name: '',
    gender: 1,
    age: null,
    birthDate: null,
    school: null,
    grade: null,
    class: ''
  });
  
  const rules = {
    // 验证规则省略，与之前相同
  };
  
  // 响应式数据
  const dataSource = ref([]);
  const searchText = ref('');
  const showModal = ref(false);
  const modalType = ref('add');
  const confirmLoading = ref(false);
  const formRef = ref();
  
 
  
  // 方法
  const formatDate = (date) => {
    return dayjs(date).format('YYYY-MM-DD');
  };
  
  const calculateAge = (birthDate) => {
    if (!birthDate) return null;
    return dayjs().diff(dayjs(birthDate), 'year');
  };
  
  const initData = () => {
    // 初始化数据逻辑省略，与之前相同
  };
  
  const handleSearch = () => {
    pagination.current = 1;
  };
  
  const handleOk = async () => {
    try {
      await formRef.value.validate();
      confirmLoading.value = true;
      
      // 计算年龄
      if (formState.birthDate && !formState.age) {
        formState.age = calculateAge(formState.birthDate);
      }
      
      // 模拟异步操作
      setTimeout(() => {
        if (modalType.value === 'add') {
          // 新增逻辑
          const newId = dataSource.value.length > 0 
            ? Math.max(...dataSource.value.map(item => item.id)) + 1 
            : 1;
          dataSource.value.unshift({
            ...formState,
            id: newId
          });
          message.success('新增学生成功');
        } else {
          // 编辑逻辑
          const index = dataSource.value.findIndex(item => item.id === formState.id);
          if (index !== -1) {
            dataSource.value[index] = { ...formState };
            message.success('更新学生信息成功');
          }
        }
        
        confirmLoading.value = false;
        showModal.value = false;
        formRef.value.resetFields();
      }, 800);
    } catch (error) {
      console.log('验证失败:', error);
    }
  };
  
  const handleCancel = () => {
    formRef.value.resetFields();
    showModal.value = false;
  };
  
  const handleDelete = (id) => {
    // 删除逻辑省略，与之前相同
  };
  
const currentTime = ref("2025-04-09 16:25:18 星期三");
const currentCity = ref("");
const typeList = ref()
const mood = ref("2");
const moodText = ref("");
const isdelFun = ref(false);
const listss = ref([]);
const records = ref([
  // {
  //   time: "2025-01-25 08:42:10",
  //   location: "唐山市",
  //   mood: "微笑",
  //   text: "清晨的粥比夜晚的酒好喝，骗你的人比爱你的人会说",
  // },
  // {
  //   time: "2025-01-25 08:14:33",
  //   location: "唐山市",
  //   mood: "呲牙",
  //   text: "放假了",
  // },
  // {
  //   time: "2025-01-14 22:27:37",
  //   location: "北京市",
  //   mood: "微笑",
  //   text: "再见2024，你好2025",
  // },
  // {
  //   time: "2025-01-01 22:14:13",
  //   location: "西安市",
  //   mood: "微笑",
  //   text: "",
  // },
]);
const chartRef = ref(null);
const timeRange = ref("day");
function filterByTimeRange(data, range) {
  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth();
  const currentDay = now.getDate();
  const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay()));
  const lastDayOfWeek = new Date(firstDayOfWeek);
  lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 6);

  return data.filter((item) => {
    const createDate = new Date(item.creatTime);
    switch (range) {
      case "thisWeek":
        return createDate >= firstDayOfWeek && createDate <= lastDayOfWeek;
      case "thisMonth":
        return (
          createDate.getFullYear() === currentYear &&
          createDate.getMonth() === currentMonth
        );
      case "thisYear":
        return createDate.getFullYear() === currentYear;
      default:
        return false;
    }
  });
}

const initChart = (type) => {
  const chart = echarts.init(chartRef.value);
  typeList.value = type
  console.log(type);
  // const { xData, yData } = generateData(timeRange.value);
  let xData = [];
  let yData = [];
  let list = [];
  if (type == "thisWeek") {
    list = filterByTimeRange(listss.value, "thisWeek");
  }
  if (type == "thisMonth") {
    list = filterByTimeRange(listss.value, "thisMonth");
  }
  if (type == "thisYear") {
    list = filterByTimeRange(listss.value, "thisYear");
  }

  list.forEach((item) => {
    xData.push(item.creatTime);
    yData.push(item.moodIndex);
  });
  const option = {
    xAxis: {
      type: "category",
      data: xData,
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: function (value) {
          // 根据数值范围返回对应的中文描述
          if (value === 0) {
            return "";
          }
          if (value === 1) {
            return "狂喜";
          } else if (value === 2) {
            return "开心";
          } else if (value === 3) {
            return "一般";
          } else if (value === 4) {
            return "伤心";
          } else if (value === 5) {
            return "难过";
          }
          return value;
        },
      },
    },
    series: [
      {
        data: yData,
        type: "line",
      },
    ],
  };
  chart.setOption(option);
};

const changeTimeRange = (range) => {
  timeRange.value = range;
  initChart();
};
const recordMood = () => {
  let data = {
    description: moodText.value,
    moodIndex: mood.value,
    userId: JSON.parse(sessionStorage.getItem("user")).id,
  };
  addMood(data).then((res) => {
    if (res.code == 200) {
      selectMoodFun();
    }
  });
};
const updateClock = () => {
  const now = new Date();

  // 获取年月日时分秒
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  const day = now.getDate().toString().padStart(2, "0");
  const hours = now.getHours().toString().padStart(2, "0");
  const minutes = now.getMinutes().toString().padStart(2, "0");
  const seconds = now.getSeconds().toString().padStart(2, "0");

  // 格式化输出
  const time = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  currentTime.value = time;
};
const selectMoodFun = () => {
  let data = {
    userId: JSON.parse(sessionStorage.getItem("user")).id,
  };
  selectMood(data).then((res) => {
    if (res.code == 200) {
      records.value = res.data;
    }
  });
};
const delFun = (val) => {
  // val.isdelFun = !val.isdelFun;
  if (val.isdelFun) {
    val.isdelFun = false;
    let data = {
      ...val,
    };
    updateMood(data).then((res) => {
      if (res.code == 200) {
        selectMoodFun();
      }
    });
  } else {
    val.isdelFun = true;
  }
  console.log(val);
  if (val.isdelFun) {
  }
};
onMounted(() => {
  updateClock();
  selectMoodFun();
  setInterval(updateClock, 1000);

  histogram().then((res) => {
    let list = Object.keys(res.data);
    list.forEach((item) => {
      if (JSON.parse(sessionStorage.getItem("user")).userName == item) {
        listss.value = res.data[item];
        initChart("thisWeek");
      }
    });
  });
  const day = new Date().getDay(); // 返回0(周日)到6(周六)的数字
  const weekdays = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];
  currentCity.value = weekdays[day];
});
</script>

<style scoped>
.app-container {
  font-family: Arial, sans-serif;
  background-color: #fff;
  line-height: 1.6;
  padding: 10px;
  height: 99vh;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e0e0e0;
}

.header-time {
  font-size: 14px;
  color: #333;
}

.mood-input {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.mood-input select {
  margin-right: 10px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.mood-input input {
  flex: 1;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.mood-input button {
  margin-left: 10px;
  padding: 5px 10px;
  background-color: #f4f4f4;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.access-data {
  margin: 10px 0;
}

.timeline {
  margin: 10px 0;
  padding-left: 20px;
  position: relative;
}

.timeline::before {
  content: "";
  position: absolute;
  left: 16px;
  top: 0;
  width: 2px;
  height: 100%;
  background-color: #e0e0e0;
}

.timeline-item {
  margin-bottom: 10px;
  display: flex;
  padding: 10px;
  margin-left: 20px;
  background: #fff;
  //background-color: #f9f9f9;
  border-radius: 5px;
  position: relative;
  box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.1);
}

.timeline-item::before {
  content: "";
  position: absolute;
  left: -30px;
  top: -27px;
  width: 14px;
  height: 14px;
  background-color: #e0e0e0;
  border-radius: 50%;
}

.timeline-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #777;
  margin-bottom: 5px;
}

.timeline-item-content {
  font-size: 14px;
  width: 100%;
  text-align: left;
  color: #333;
  padding-left: 20px;
}
.timeline-date {
  display: inline-block;
  width: 100%;
  text-align: left;
  margin-bottom: 10px;
  margin-left: 20px;
}
</style>
